#include "StdAfx.h"
#include "DeskTopC.h"

ScreenHeader DeskTopC::m_screenHeader;
static Rgb2JpegScreen lpImage;
void CALLBACK DeskTopC::threadWork_1(SOCKET s)
{
	if(Auth(s,11111) < 0)
		return;

	while (TRUE)
	{	
		LPSTR lpData = NULL;
		lpImage.Init(m_screenHeader.rcArea,m_screenHeader.nArea);
		lpData = (LPSTR)lpImage.GetScreeenData(m_screenHeader);
		MessageHeader header2;
		memset(&header2,0,sizeof(MessageHeader));
		header2.channelID = 11111;
		header2.length = sizeof(ScreenHeader)+m_screenHeader.dwFileSize;
		header2.packageType = NORMAL;
		header2.version = 0x19780927;
		int ret = send(s,(char*)&header2,sizeof(header2),0);
		if (ret == SOCKET_ERROR)
		{
			return;
		}
		ret = -1;
	    ret = send(s,(char*)&m_screenHeader,sizeof(ScreenHeader),0);
		int sen = 0;
		char * p = (char*)lpData;
		while(sen < m_screenHeader.dwFileSize)
		{
			int ret = send(s,p,m_screenHeader.dwFileSize-sen,0);
			p += ret; 
			if (ret <0)
			{
				break;

			}
			sen += ret;
		}

		if (lpData)
		{
			GlobalFree(lpData);
		}

		Sleep(m_screenHeader.nDelay);
	}
}
int DeskTopC::start(ScreenHeader& head,char* ip,int port)
{
	m_screenHeader = head;
	return client.StartClient(ip,port,threadWork_1);
}
int DeskTopC::Auth(SOCKET client,unsigned int channelID)
{
	MessageHeader header;
	memset(&header,0,sizeof(header));
	header.packageType = AUTH;
	header.channelID = 11111;
	header.length = 12;
	header.version = 0x19780927;
	struct Msg{
		MessageHeader head;
		int ownerID;
		int groupID;
		int channelID;
	};
	Msg g_msg;
	g_msg.head = header;
	g_msg.groupID = 1;
	g_msg.ownerID = 12345;
	g_msg.channelID = 11111;
	int ret = send(client, (char*)&g_msg, sizeof(Msg), 0);
	if (ret == SOCKET_ERROR)
	{
		return -1;
	}
	memset(&header,0,sizeof(header));
	ret = -1;
	ret = recv(client, (char*)&header, sizeof(MessageHeader), 0);
	if (ret == SOCKET_ERROR)
	{
		return -1;
	}
	if (header.packageType == AUTH_SUCCESS)
	{
		return 1;
	}

	return 0;
}